import { constantRoutersMap, asyncRoutesMap } from "@/router";
import { getRoutes } from "@/api/role";
import Layout from "@/layout";

export function filterAsyncRoutes(routes) {
  const res = [];

  routes.forEach(route => {
    const tmp = { ...route };
    if (tmp.children && !tmp.hidden) {
      tmp.children = filterAsyncRoutes(tmp.children);
    }
    res.push(tmp);
  });

  return res;
}

const state = {
  //左侧按钮列表--------------------------------------------
  menuList: [],
  //总路由列表--------------------------------------------
  routes: [],
  //动态添加路由列表--------------------------------------------
  addRoutes: [],
  activeMenu: {},
  //页面内自定义按钮列表menuRouteUrl==2--------------------------------------------
  pageBtn: [],
  //页面内顶部按钮页面内按钮列表menuRouteUrl==1--------------------------------------------
  pageTopBtn: []
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutersMap.concat(routes);
  },
  SET_MENU_LIST: (state, menu) => {
    state.menuList = menu;
  },
  SET_MENU_ID: (state, obj) => {
    state.activeMenu = obj;
  },
  SET_PAGE_BTN: (state, params) => {
    state.pageBtn = params;
  },
  SET_PAGE_TOP_BTN: (state, params) => {
    state.pageTopBtn = params;
  },
  LOGOUT: state => {
    //左侧按钮列表--------------------------------------------
    state.menuList = [];
    //总路由列表--------------------------------------------
    state.routes = [];
    //动态添加路由列表--------------------------------------------
    state.addRoutes = [];
    state.activeMenu = {};
    //页面内自定义按钮列表menuRouteUrl==2--------------------------------------------
    state.pageBtn = [];
    //页面内顶部按钮页面内按钮列表menuRouteUrl==1--------------------------------------------
    state.pageTopBtn = [];
  }
};

const actions = {
  generateRoutes({ commit }, params) {
    return new Promise(resolves => {
      getRoutes(params)
        .then(response => {
          const { items } = response;
          const routes =
            items &&
            items.map(route => {
              return {
                path: route.menuRouteUrl,
                meta: {
                  icon: route.icoClass || "el-icon-folder",
                  title: route.child.length === 0 ? "" : route.menuName,
                  mid: route.id || null,
                  keepAlive: true
                },
                name: route.menuRouteUrl,
                redirect: redirectFn(route),
                component: Layout,
                children: childrenFn(route)
              };
            });
          let indexPath = [];
          if (routes.length != 0) {
            indexPath = [
              {
                path: "/",
                component: Layout,
                redirect: routes[0].path
              }
            ];
          }
          const accessedRoutes = indexPath
            .concat(routes)
            .concat(asyncRoutesMap);
          commit("SET_MENU_LIST", accessedRoutes);
          commit("SET_ROUTES", accessedRoutes);
          resolves(accessedRoutes);
        })
        .catch(err => {
          console.log(err);
        });
    });
  },
  setMenuId({ commit }, activeMenu) {
    commit("SET_MENU_ID", activeMenu);
  },
  setPageBtn({ commit }, params) {
    commit("SET_PAGE_BTN", params);
  },
  setPageTopBtn({ commit }, params) {
    commit("SET_PAGE_TOP_BTN", params);
  }
};

function childrenFn(route) {
  if (route.child.length === 0) {
    return [
      {
        path: route.menuRouteUrl + "/index",
        parentId: 0,
        meta: {
          icon: route.icoClass || "el-icon-folder",
          title: route.menuName,
          mid: route.id || null,
          keepAlive: true
        },
        name: route.menuRouteUrl + "/index",
        component: resolve => {
          require(["@/views" + route.menuUrl], resolve);
        }
      }
    ];
  } else {
    return route.child.map(childRoute => {
      const routerName =
        route.menuRouteUrl +
        "_" +
        (childRoute.menuRouteUrl.indexOf("?") > -1
          ? childRoute.menuRouteUrl.substring(
              0,
              childRoute.menuRouteUrl.indexOf("?")
            )
          : childRoute.menuRouteUrl);

      return {
        path: childRoute.menuRouteUrl,
        meta: {
          mid: childRoute.id,
          icon: "ios-paper-outline",
          title: childRoute.menuName,
          keepAlive: true
        },
        name: routerName,
        component: resolve => {
          require(["@/views" + childRoute.menuUrl], resolve);
        }
      };
    });
  }
}

function redirectFn(route) {
  if (route.child.length === 0) {
    return route.menuRouteUrl + "/index";
  } else {
    return route.child[0].menuRouteUrl;
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
